﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace peonwar
{
    static class Security
    {
        static public void WriteCipher(string filename)
        {
            StreamReader reader = new StreamReader(File.Open(SettingManager.GamePath + "Content/Profils/temp", FileMode.Open, FileAccess.Read));
            string text = reader.ReadToEnd();
            reader.Close();

            string key = Hash(filename);

            StreamWriter writer = new StreamWriter(File.Create(SettingManager.GamePath + "Content/Profils/" + filename));

            for (int i = 0; i < text.Length; i++)
            {
                char m = text[i];
                char k = key[i % key.Length];
                char r = (char)(((int)m + (int)k) % 255);

                writer.Write(r);
            }
            writer.Close();
            File.Delete(SettingManager.GamePath + "Content/Profils/temp");
        }

        static public void ReadDecipher(string filename)
        {
            StreamReader reader = new StreamReader(File.Open(SettingManager.GamePath + "Content/Profils/" + filename, FileMode.Open, FileAccess.Read));
            string text = reader.ReadToEnd();
            reader.Close();

            string key = Hash(filename);
            StreamWriter writer = new StreamWriter(File.Create(SettingManager.GamePath + "Content/Profils/temp"));

            for (int i = 0; i < text.Length; i++)
            {
                char m = text[i];
                char k = key[i % key.Length];
                char r = (char)(((int)m - (int)k) % 255);

                writer.Write(r);
            }
            writer.Close();
        }

        static public string Hash(string text)
        {
            if (text == "")
                throw new Exception("Cannot make a Hash with empty token");

            string original = text;
            text = text.ToLower();
            int sum = 0;
            int rot = 0;

            while (text.Length < 512)
            {
                text += text;
                rot++;
            }

            for (int o = 0; o < original.Length; o++)
            {
                sum += (int)original[o];
            }
            sum *= rot;

            int[] result = new int[16];

            sum = sum % text.Length;

            for (int i = 0; i < text.Length; i++)
            {
                int t = (int)text[i];
                int v = (result[(i + 1) % 16] * t + sum) % 127;
                if (v == 7)
                    v++;

                result[i % 16] = v;
            }

            string final = "";
            for (int l = 0; l < 16; l++)
                final += (char)result[l];
            return final;
        }
    }
}
